#include "statemanager.h"
#include <QDebug>

StateManager& StateManager::instance() {
    static StateManager inst;
    return inst;
}

StateManager::StateManager(QObject* parent)
    : QObject(parent)
{
}

void StateManager::setState(const QString& key, StateType type, const QString& description) {
    auto it = m_states.find(key);
    bool changed = false;

    if (it == m_states.end()) {
        changed = true;
    } else {
        const auto& old = it.value();
        if (old.type != type || old.description != description)
            changed = true;
    }

    if (changed) {
        StateInfo info(type, description);
        m_states[key] = info;
        emit stateChanged(key, info);

        qDebug().noquote() << QString("[State] %-15s Type:%1  Desc:%2")
                              .arg(key)
                              .arg(static_cast<int>(type))
                              .arg(description);
    }
}

StateInfo StateManager::getState(const QString& key) const {
    return m_states.value(key, StateInfo());
}

void StateManager::clearState(const QString& key) {
    if (m_states.remove(key) > 0) {
        emit stateCleared(key);
        qDebug() << "[State Cleared]" << key;
    }
}

QMap<QString, StateInfo> StateManager::allStates() const {
    return m_states;
}

void StateManager::printAllStates() const {
    if (m_states.isEmpty()) {
        qDebug() << " 当前没有任何状态。";
        return;
    }

    qDebug().noquote() << "=== 系统当前状态 ===";
    for (auto it = m_states.constBegin(); it != m_states.constEnd(); ++it) {
        const auto& info = it.value();
        qDebug().noquote()
            << QString("Key: %-15s | Type: %1 | Time: %2 | Desc: %3")
                   .arg(it.key())
                   .arg(static_cast<int>(info.type))
                   .arg(info.timestamp.toString("hh:mm:ss"))
                   .arg(info.description);
    }
    qDebug() << "========================";
}
